package me.zhengjie.open;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhengjie.annotation.rest.AnonymousGetMapping;

import me.zhengjie.open.utils.FireFoxHttpUtils;
import me.zhengjie.open.utils.PlateFormToken;
import me.zhengjie.open.utils.PomeloHttpUtils;
import me.zhengjie.open.utils.TimeUtils;
import me.zhengjie.phone.domain.SmsPhone;
import me.zhengjie.phone.mapper.SmsPhoneMapper;
import me.zhengjie.phone.service.SmsPhoneService;
import me.zhengjie.sms.domain.SmsUser;
import me.zhengjie.sms.domain.vo.SmsUserQueryCriteria;
import me.zhengjie.sms.mapper.SmsUserMapper;
import me.zhengjie.sms.service.SmsUserService;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author yushaopeng
 * @Package me.zhengjie.open
 * @Description:
 * @date 2025/1/8 18:40
 */

@Controller
@RequestMapping("/open")
public class OpenController {

    @Autowired
    SmsUserMapper smsUserMapper;

    @Autowired
    SmsPhoneMapper smsPhoneMapper;




    @AnonymousGetMapping("/hello")
    public String hello(){
        return "hello";
    }


    @AnonymousGetMapping("/gen")
    public ResponseEntity<String> gen(@RequestParam(value = "token", required = true, defaultValue = "") String param1) {
        // 处理逻辑
        // 1.查看是否超过请求次数
        // 2.没有超过就请求手机号入库并生成smsphonetoken和手机号
        LambdaQueryWrapper<SmsUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SmsUser::getSmsUserToken, param1);
        List<SmsUser> list =smsUserMapper.selectList(lambdaQueryWrapper);
        if (list!=null&&list.size()>0){
            int limit = Integer.valueOf(list.get(0).getSmsUserLimit());
            LambdaQueryWrapper<SmsPhone> phonewrapper = new LambdaQueryWrapper<>();
            phonewrapper.eq(SmsPhone::getSmsUserToken, param1);
            long use = smsPhoneMapper.selectCount(phonewrapper);
            if (use >= limit){
                return ResponseEntity.badRequest().body("超过使用限制");
            }else{

                if ("0".equals(list.get(0).getSmsPlatformType())) {

                    String result = FireFoxHttpUtils.getPhone(list.get(0).getSmsCountry(), list.get(0).getSmsIid());
                    if (result != null && !"".equals(result)) {

                        String[] columns = result.split("\\|");
                        if (columns.length > 2) {
                            SmsPhone temp = new SmsPhone();
                            temp.setSmsUserToken(param1);
                            temp.setSmsPhoneToken("PHONE" + UUID.randomUUID().toString());
                            temp.setSmsPlatformToken(PlateFormToken.getPlateformTokken(0));
                            temp.setSmsPhoneNumber(columns[7]);
                            temp.setSmsPhoneKey(columns[1]);
                            temp.setSmsPhoneCreateTime(new Timestamp(System.currentTimeMillis()));
                            temp.setSmsPhoneCountryCode(columns[3]);
                            temp.setSmsPhoneAreaCode(columns[4]);
                            temp.setSmsPhonePosition(columns[5]);
                            temp.setSmsPhonePort(columns[6]);
                            try {
                                temp.setSmsPhoneAcceptCode(columns[8]);
                            } catch (Exception e) {

                            }
                            temp.setSmsOriginal(result);
                            temp.setSmsPhoneStatus("-3");

                            smsPhoneMapper.insert(temp);

                            return ResponseEntity.ok(temp.getSmsPhoneToken() + "|" + temp.getSmsPhoneNumber());

                        } else {
                            return ResponseEntity.badRequest().body("获取手机号失败");
                        }

                    } else {
                        return ResponseEntity.badRequest().body("获取手机号失败");
                    }
                }else if("1".equals(list.get(0).getSmsPlatformType())){
                    try {
                        String result = PomeloHttpUtils.getPhoneNumber(list.get(0).getSmsCountry(), list.get(0).getSmsIid());
                        JSONObject jsonObject = JSON.parseObject(result);
                        if(((JSONObject)jsonObject.get("data")).get("orderId")!=null){
                            SmsPhone temp = new SmsPhone();
                            temp.setSmsUserToken(param1);
                            temp.setSmsPhoneToken("PHONE" + UUID.randomUUID().toString());
                            temp.setSmsPlatformToken(PomeloHttpUtils.SECRET_KEY);
                            temp.setSmsPhoneNumber((String) ((JSONObject)jsonObject.get("data")).get("phone"));
                            temp.setSmsPhoneKey((String) ((JSONObject)jsonObject.get("data")).get("orderId"));
                            temp.setSmsPhoneCreateTime(new Timestamp(System.currentTimeMillis()));
//                            temp.setSmsPhoneCountryCode(columns[3]);
//                            temp.setSmsPhoneAreaCode(columns[4]);
//                            temp.setSmsPhonePosition(columns[5]);
//                            temp.setSmsPhonePort(columns[6]);
//                            try {
//                                temp.setSmsPhoneAcceptCode(columns[8]);
//                            } catch (Exception e) {
//
//                            }
                            temp.setSmsOriginal(result);
                            temp.setSmsPhoneStatus("-3");

                            smsPhoneMapper.insert(temp);
                            return ResponseEntity.ok(temp.getSmsPhoneToken() + "|" + temp.getSmsPhoneNumber());
                        }else {
                            return ResponseEntity.badRequest().body("获取手机号失败");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        return ResponseEntity.badRequest().body("获取手机号失败");
                    }
                }

            }
        }else {
            return ResponseEntity.badRequest().body("用户不存在");
        }



        return ResponseEntity.badRequest().body("获取手机号失败");



    }

    // 获取验证码
    @AnonymousGetMapping("/smscode")
    @Transactional
    public ResponseEntity<String> getSmsCode(@RequestParam(value = "token", required = true, defaultValue = "") String param1) {
        // 处理逻辑
        // 根据token去获取smsphone的pkey然后请求firefox返回
        Map<String, Object> params = new HashMap<>();
        params.put("sms_phone_token", param1);
        List<SmsPhone> results = smsPhoneMapper.selectByMap(params);
        if (results!=null&&results.size()>0){
            //判断时间是不是超过五分钟了
            long timestap = results.get(0).getSmsPhoneCreateTime().getTime();
            long now = System.currentTimeMillis();
            if ((now-timestap)>300000){
                //超过5分钟 需要释放手机号
                return ResponseEntity.badRequest().body("手机号已释放");
            }else{
                //获取验证码
                LambdaQueryWrapper<SmsUser> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(SmsUser::getSmsUserToken, results.get(0).getSmsUserToken());
                List<SmsUser> secondlist = smsUserMapper.selectList(lambdaQueryWrapper2);
                if (secondlist != null && secondlist.size() > 0) {

                    if ("0".equals(secondlist.get(0).getSmsPlatformType())){
                        String s = FireFoxHttpUtils.getSmsCode(results.get(0).getSmsPhoneKey());
                        if (s.split("\\|").length>2){
                            List<SmsUser> thirdList = smsUserMapper.selectList(lambdaQueryWrapper2);
                            secondlist.get(0).setSmsUserUse((
                                    Integer.valueOf(thirdList.get(0).getSmsUserUse())
                                            + 1) + "");

                            smsUserMapper.updateById(thirdList.get(0));
                            return ResponseEntity.ok(s.split("\\|")[0]);
                        }else{

//                            if (s.contains("-3")) {
                                return ResponseEntity.badRequest().body("正在接收短信");
//                            }else{
//                                return ResponseEntity.badRequest().body("接收验证码出错，联系管理员");
//                            }
                        }


                    } else if("1".equals(secondlist.get(0).getSmsPlatformType())){

                        Map map = new HashMap();
                        map.put("orderId",results.get(0).getSmsPhoneKey());
                        try {
                            String result = PomeloHttpUtils.getSms(map);
                            JSONObject jsonObject = JSON.parseObject(result);
                            if(((JSONObject)jsonObject.get("data")).get("code")!=null){
                                List<SmsUser> thirdList = smsUserMapper.selectList(lambdaQueryWrapper2);
                                secondlist.get(0).setSmsUserUse((
                                        Integer.valueOf(thirdList.get(0).getSmsUserUse())
                                                + 1) + "");

                                smsUserMapper.updateById(thirdList.get(0));
                                return ResponseEntity.ok((String) ((JSONObject)jsonObject.get("data")).get("code"));


                            }else {
                                return ResponseEntity.badRequest().body("正在接收短信");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            return ResponseEntity.badRequest().body("正在接收短信");
                        }

                    }




                }

            }
        }else {
            return ResponseEntity.badRequest().body("手机号不存在");
        }

        return ResponseEntity.badRequest().body("手机号不存在");
//        return ResponseEntity.ok("Received param1: " + param1);
    }





    //拉黑手机
    @AnonymousGetMapping("/blacksms")
    public ResponseEntity<String> block(@RequestParam(value = "token", required = true, defaultValue = "") String param1) {
        Map<String, Object> params = new HashMap<>();
        params.put("sms_phone_token", param1);
        List<SmsPhone> results = smsPhoneMapper.selectByMap(params);
        if (results!=null&&results.size()>0){
            //拉黑手机号

            LambdaQueryWrapper<SmsUser> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(SmsUser::getSmsUserToken, results.get(0).getSmsUserToken());
            List<SmsUser> secondlist = smsUserMapper.selectList(lambdaQueryWrapper2);
            if (secondlist != null && secondlist.size() > 0) {
                if ("0".equals(secondlist.get(0).getSmsPlatformType())) {
                    FireFoxHttpUtils.blocksms(results.get(0).getSmsPhoneKey());
                    return ResponseEntity.ok("手机号已拉黑");
                }else if ("1".equals(secondlist.get(0).getSmsPlatformType())){

                    try {
                        PomeloHttpUtils.releasePhone(results.get(0).getSmsPhoneKey());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        return ResponseEntity.ok("手机号已拉黑");
                    }
                }
            }else {
                return ResponseEntity.badRequest().body("手机号不存在");
            }

        }else {
            return ResponseEntity.badRequest().body("手机号不存在");
        }

        return ResponseEntity.badRequest().body("手机号不存在");
//        return ResponseEntity.ok("Received param1: " + param1);
    }


}
